﻿using System;
using System.IO;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using ITViet.Data;
using ITViet.Web.App_Code;
using ITViet.Services;
using ITViet.Domains;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxUploadControl;

namespace ITViet.Web.Admin
{
  public partial class NewsLetterList : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;

    protected string ListNewsLetter = string.Empty;
    protected string UploadCompleteFunction = "attachFile";
    protected string UploadSessionName = SessionName.UploadContainPostedFile;
    protected string UploadFolder = FolderDirector.TempFolder;

    internal override int RequiredPermission
    {
      get
      {
        //return (int)FunctionList.Newsletter;
        return 0;
      }
    }
    #endregion

    #region Private Methods

    #region Email List
    private void LoadList()
    {
      TList<Domains.NewsLetter> ds = new NewsLetterService().GetAll();
      gvList.DataSource = ds;
      gvList.DataBind();
    }

    private string SaveItem(int itemId, string email, string customerName, string note)
    {
      try
      {
        NewsLetterService service = new NewsLetterService();
        Domains.NewsLetter item = null;
        if (itemId > 0)
        {
          item = service.GetById(itemId);
          if (item == null)
            return Resources.Messages.ERR0003;
        }
        else
        {
          item = service.GetByEmail(email);
          if (item != null)
            return Resources.Messages.ERR0026;
          item = new Domains.NewsLetter();
        }
        item.Email = email;
        item.Note = note;
        item.CustomerName = customerName;
        service.Save(item);
      }
      catch (Exception ex)
      {
        WriteLog("NewsLetterEmail.aspx::Save Item", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string DeleteItem(int itemId)
    {
      try
      {
        new NewsLetterService().Delete(itemId);
      }
      catch (Exception ex)
      {
        WriteLog("NewsLetterEmail.aspx::Delete Item", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private void LoadEmail()
    {
      TList<Domains.NewsLetter> listNewsLetter = new NewsLetterService().GetAll();
      string result = string.Empty;
      foreach (Domains.NewsLetter letter in listNewsLetter)
      {
        if (string.IsNullOrEmpty(result))
        {
          result += "{Email: \"" + letter.Email + "\"}";
        }
        else
        {
          result += ", " + "{Email: \"" + letter.Email + "\"}";
        }
      }

      ListNewsLetter = "[" + result + "]";
    }
    #endregion

    #region Compose Newsletter
    private void BindFileGrid()
    {
      DataTable tbl = null;
      if (Session[SessionName.UploadFolder] == null)
        Session[SessionName.UploadFolder] = UploadFolder;
      if (Session[SessionName.EmailAttachFile] != null)
        tbl = Session[SessionName.EmailAttachFile] as DataTable;
      if (tbl == null)
      {
        tbl = new DataTable("Attachment");
        tbl.Columns.Add(new DataColumn(("FileName"), Type.GetType("System.String")));
        tbl.Columns.Add(new DataColumn(("FilePath"), Type.GetType("System.String")));
        tbl.PrimaryKey = new DataColumn[] { tbl.Columns["FilePath"] };
        Session[SessionName.EmailAttachFile] = tbl;
      }
      gvFile.DataSource = tbl;
      gvFile.DataBind();
    }

    private void LoadSelect()
    {
      TList<Domains.NewsLetter> ds = new NewsLetterService().GetAll();
      gvSelect.DataSource = ds;
      gvSelect.DataBind();
    }

    private string SendNewsletter()
    {
      try
      {
        string[] toEmails = null;
        string[] ccEmails = null;
        string[] bccEmails = null;
        string[] attchment = null;
        string subject = txtSubject.Text;
        string content = htmlEditor.Html;
        string emails = string.Empty;

        //To Email
        emails = txtTo.Value;
        if (emails.EndsWith(";"))
          emails = emails.Remove(emails.Length - 1);
        if (!string.IsNullOrEmpty(emails))
          toEmails = emails.Split(';');

        //Cc Email
        emails = txtCC.Value;
        if (emails.EndsWith(";"))
          emails = emails.Remove(emails.Length - 1);
        if (!string.IsNullOrEmpty(emails))
          ccEmails = emails.Split(';');

        //Bcc Email
        emails = txtBCC.Value;
        if (emails.EndsWith(";"))
          emails = emails.Remove(emails.Length - 1);
        if (!string.IsNullOrEmpty(emails))
          bccEmails = emails.Split(';');

        //Attachment
        if (gvFile.VisibleRowCount > 0)
        {
          attchment = new string[gvFile.VisibleRowCount];
          for (int i = 0; i < gvFile.VisibleRowCount; i++)
          {
            string filePath = gvFile.GetRowValues(i, "FilePath").ToString();
            attchment[i] = filePath;
          }
        }

        System.Net.Mail.MailMessage message = SendMail.PrepareMailMessage(toEmails, ccEmails, bccEmails, subject, content, attchment);
        SendMail.StartSendMail(message);
        //if (attchment != null)
        //{
        //  foreach (string filePath in attchment)
        //  {
        //    if (File.Exists(filePath))
        //    {
        //      File.Delete(filePath);
        //    }
        //  }
        //}
      }
      catch (Exception ex)
      {
        WriteLog("Newsletter.aspx::Send Newsletter", ex);
        return Resources.Messages.ERR0030;
      }
      return string.Empty;
    }
    #endregion
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsCallback && !IsPostBack)
      {
        Session[SessionName.EmailAttachFile] = null;
        LoadList();
        BindFileGrid();
        LoadEmail();
      }
      if (gvList.IsCallback)
        LoadList();
    }

    protected void gvList_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
      if (!string.IsNullOrEmpty(e.Parameters))
        LoadList();
    }

    protected void gvList_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvList_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      m_innerError = DeleteItem(id);
      e.Cancel = true;
      ASPxGridView gridControl = sender as ASPxGridView;
      gridControl.CancelEdit();
      LoadList();
    }

    protected void gvList_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
      string email = (e.NewValues["Email"] != null) ? e.NewValues["Email"].ToString() : string.Empty;
      string note = (e.NewValues["Note"] != null) ? e.NewValues["Note"].ToString() : string.Empty;
      string customerName = (e.NewValues["CustomerName"] != null) ? e.NewValues["CustomerName"].ToString() : string.Empty;

      if (string.IsNullOrEmpty(email))
        m_innerError = string.Format(/*Resources.Messages.ERR0025*/ null, Resources.Strings.Email);
      else if (!Utils.ValidateEmail(email))
        m_innerError = Resources.Messages.ERR0029;
      else
        m_innerError = SaveItem(-1, email, customerName, note);
      e.Cancel = true;
      ASPxGridView gridControl = sender as ASPxGridView;
      gridControl.CancelEdit();
      LoadList();
    }

    protected void gvList_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      string email = (e.NewValues["Email"] != null) ? e.NewValues["Email"].ToString() : string.Empty;
      string note = (e.NewValues["Note"] != null) ? e.NewValues["Note"].ToString() : string.Empty;
      string customerName = (e.NewValues["CustomerName"] != null) ? e.NewValues["CustomerName"].ToString() : string.Empty;

      if (string.IsNullOrEmpty(email))
        m_innerError = string.Format(/*Resources.Messages.ERR0025*/ null, Resources.Strings.Email);
      else if (!Utils.ValidateEmail(email))
        m_innerError = Resources.Messages.ERR0029;
      else
        m_innerError = SaveItem(id, email, customerName, note);
      e.Cancel = true;
      ASPxGridView gridControl = sender as ASPxGridView;
      gridControl.CancelEdit();
      LoadList();
    }

    protected void gvSelect_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      LoadSelect();
    }

    protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      e.Result = SendNewsletter();
    }

    protected void gvFile_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      if (para[0] == "Save")
      {
        string file = para[1];
        DataTable tbl = Session[SessionName.EmailAttachFile] as DataTable;
        if (tbl == null)
          return;
        string uploadedList = string.Empty;
        if (Session[SessionName.UploadReturnFiles] != null)
          uploadedList = Session[SessionName.UploadReturnFiles].ToString();
        if (!string.IsNullOrEmpty(uploadedList))
        {
          string[] fileList = uploadedList.Split(';');
          if (fileList != null)
          {
            for (int i = 0; i < fileList.Length; i++)
            {
              if (string.IsNullOrEmpty(fileList[i]))
                continue;
              int count = fileList[i].LastIndexOf('/') + 1;
              string fileName = fileList[i].Remove(0, count);
              count = fileName.IndexOf('_') + 1;
              fileName = fileName.Remove(0, count);
              DataRow newFile = tbl.NewRow();
              newFile["FileName"] = fileName;
              newFile["FilePath"] = MapPath("../" + fileList[i]);
              tbl.Rows.Add(newFile);

            }
          }
          ClearSession(new string[] { SessionName.UploadReturnFiles, SessionName.UploadContainPostedFile });
          BindFileGrid();
        }
      }
    }

    protected void gvFile_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      ASPxGridView grid = sender as ASPxGridView;
      DataTable tbl = Session[SessionName.EmailAttachFile] as DataTable;
      if (tbl != null)
      {
        string filePath = e.Keys["FilePath"].ToString();
        DataRow row = tbl.Rows.Find(filePath);
        if (row != null)
          tbl.Rows.Remove(row);
      }
      e.Cancel = true;
      grid.CancelEdit();
      BindFileGrid();
    }
    #endregion
  }
}
